<template>
  <div class="log-list flex-1 flex flex-col h-0">
    <div class="log-list__header flex justify-between items-center">
      <span class="log-list__header--title">{{$t('custom.apiList')}}</span>

      <el-select clearable
                 @change="getLogs"
                 v-model="searchForm.status">
        <el-option v-for="(record,index) in logStatus"
                   :key="index"
                   :label="$t(`custom.${record.label}`)"
                   :value="record.value"></el-option>

      </el-select>
    </div>

    <div class="log-list__content flex-1  h-0"
         ref="table-wrapper">
      <el-table :data="this.data.sync.subjectCode === 'DROPBOX' && this.data.auth === 'user'?[]:tableData"
                highlight-current-row
                :height="height"
                row-key="id"
                ref="table"
                @row-click="rowClick"
                header-cell-class-name="log_list_headers">

        <el-table-column prop='action'
                         :label="$t('custom.connector.loginfo.api')"
                         header-align="center"
                         align="center"
                         width="150"></el-table-column>
        <el-table-column prop="lastSyncDate"
                         :label="$t('custom.connector.loginfo.lastSycnTime')"
                         header-align="center"
                         align="center">
          <template slot-scope="scope">{{ timeAreaFormat(scope.row.lastSyncDate)}}</template>
        </el-table-column>
        <el-table-column prop="status"
                         :label="$t('custom.connector.loginfo.status')"
                         header-align="center"
                         align="center">
          <template slot-scope="scope">
            <div class="table-status"
                 :class="statusStyle(scope.row)">{{getStatus(scope.row)}}</div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('custom.connector.loginfo.action')"
                         header-align="center"
                         align="center">
          <template slot-scope="scope">
            <div class="flex justify-center">
              <el-tooltip :open-delay="1000"
                          :content="$t('custom.syncData')">
                <el-button type="text"
                           class="table-button"
                           v-if="scope.row.apiService&&scope.row.client"
                           :disabled="!$hasPermission('sys:tenant:dataconnect:manageIntergrationSetting')"
                           :loading="scope.row.loading"
                           icon="cuifont icon_arrow_generate"
                           @click.native.stop="handleManuallySync(scope.row,scope.$index)"></el-button>
              </el-tooltip>
            </div>

          </template>

        </el-table-column>
      </el-table>
    </div>
    <z-notice :visible.sync="showNotice"
              v-bind="noticeSuccess ? noticeSuccessObject : noticeErrorObject"></z-notice>
  </div>
</template>

<script>
import { logStatus } from '../index.data'
import moment from 'moment'
import ZNotice from '@/components/storybook/z-dialog-notice'
export default {
  name: 'LogList',
  components: {
    ZNotice
  },
  props: {
    data: {
      type: Object,
      default: () => ({})
    },
    loading: {
      type: Boolean,
      default: false
    },
    historyLoading: {
      type: Boolean,
      default: false
    }

  },
  data () {
    return {
      logStatus,
      height: '200px',
      tableData: [],
      searchForm: {
        status: ''
      },
      timers: null,
      showNotice: false,
      noticeSuccess: true,
      noticeErrorObject: {
        icon: 'icon_message_alt_x',
        iconColor: '#DA1E28FF',
        title: 'Error in API permission',
        okButton: {
          text: 'Ok',
          type: 'primary'
        },
        textAlign: 'left'
      },
      noticeSuccessObject: {
        icon: 'icon_message_alt_check',
        title: 'API permission check passed',
        info: this.$t('custom.connector.successTooltip'),
        okButton: {
          text: 'Ok',
          type: 'primary'
        }
      },
      selectRow: null
    }
  },
  created () {
    this.$root.eventBus.$on('event:refresh-log', () => this.getLogs())
    this.getLogs()
  },
  beforeDestroy () {
    this.$root.eventBus.$off('event:refresh-log')
  },
  mounted () {
    this.getAutoHeight()

    window.onresize = () => {
      this.getAutoHeight()
    }
  },
  methods: {
    getWikiUrl () {
      let temp = {}
      const wikiInfoList = window.SITE_CONFIG['wikiInfo']
      let subjectCode = this.data.sync.subjectCode
      temp = this._.filter(wikiInfoList, { 'key': `${subjectCode}wiki` })
      if (temp.length > 0) {
        temp = temp[0]
      } else {
        temp = {
          url: ''
        }
      }
      return temp
    },

    getAutoHeight () {
      let el = this.$refs['table-wrapper']

      this.$nextTick(() => {
        this.height = el.clientHeight
      })
    },
    timeAreaFormat (time) {
      if (time) {
        return moment.tz(time, this.$store.state.user.timezoneId).format('MM/DD/YYYY HH:mm') + ' ' + moment.tz(time, this.$store.state.user.timezoneId).format('zz')
      }
      return time || 0
    },
    statusStyle (row) {
      if (!row.lastSyncDate && !row.status) {
        return 'status_pedding'
      }

      if (row.status === '200 OK') {
        return 'status_succes'
      }

      return 'status_nosucces'
    },
    getStatus (row) {
      if (!row.lastSyncDate && !row.status) {
        return 'Pending'
      }

      if (row.status === '200 OK') {
        return 'Succeeded'
      }

      return 'Failed'
    },
    async handleManuallySync (row, index) {
      const { get } = this._
      const { postManuallySyncAPI } = this.$interface.apiManager
      try {
        this.apiName = row.action
        row.loading = true
        this.tableData.splice(index, 1, row)
        const params = {
          tenantCode: this.$store.state.user.tenantCode,
          apiServiceName: row.apiService,
          client: row.client,
          params: {
            action: row.action
          }
        }

        let { data: response } = await postManuallySyncAPI(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.syncResult(row, index)
      } catch (error) {
        this.errorAlert(error)
        // this.$message.error(error)
      } finally {
        // row.loading = false
      }
    },
    errorAlert (msg) {
      let url = this.getWikiUrl().url
      // const url = `https://wiki.mspbots.ai/display/MKB/ConnectWise+Manage+Integrations+Setup`
      const emailLink = `mailto:support@mspbots.ai?subject=${this.data.name} sync error: Error in API permission&body=Hi MSPbots support: %0D%0Aplease help me to fix the following error, %0D%0AIntegration: ${this.data.name}%0D%0AAPI: ${this.apiName}%0D%0AError msg: ${msg}.%0D%0Athanks`
      this.noticeSuccess = false
      this.noticeErrorObject.info = this.$t('custom.connector.errorTooltip', { msg, url, emailLink })
      this.showNotice = true
    },
    async syncResult (row, index) {
      const { get } = this._
      const { getSyncResult } = this.$interface.apiManager
      try {
        const params = {
          tenantCode: this.$store.state.user.tenantCode,
          action: row.action,
          client: row.client,
          lastSyncDate: row.lastSyncDate
        }

        let { data: response } = await getSyncResult(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        } else if (response.data && response.data.status === 'OK') {
          this.noticeSuccess = true
          this.showNotice = true
        } else if (response.data && response.data.status !== 'OK') {
          this.errorAlert(response.data.msg)
        }

        if (!response.data) {
          this.syncStart(row, index)
        }

        if (response.data) {
          if (moment(row.lastSyncDate).isBefore(response.data.time)) {
            clearInterval(this.timers)
            const temp = row
            if (response.data.status === 'OK') {
              temp.status = '200 OK'
              temp.lastSyncDate = response.data.time
              temp.loading = false
              this.dataList && this.dataList.splice(index, 1, temp)
            } else {
              temp.status = 'Failed'
              temp.loading = false
              temp.lastSyncDate = response.data.time
              this.dataList && this.dataList.splice(index, 1, temp)
            }
            if (this.selectRow) {
              this.getLogsSync(this.selectRow)
            } else {
              this.getLogsSync(row)
            }
          }
        }
      } catch (error) {
        this.errorAlert(error)
        // this.$message.error(error)
      } finally {
      }
    },
    syncStart (row, index) {
      clearInterval(this.timers)
      this.timers = setInterval(() => {
        this.syncResult(row, index)
      }, 5000)
    },
    async getLogs () {
      const { get, set } = this._
      const { getConnectorDetailInfo } = this.$interface.apiManager
      const { status } = this.searchForm
      try {
        this.$emit('update:loading', true)

        const params = {
          subjectCode: get(this.data, 'sync.subjectCode')
        }

        if (status !== '') {
          set(params, 'status', status)
        }

        let { data: response } = await getConnectorDetailInfo(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.tableData = get(response, 'data', []).map(i => ({
          ...i,
          loading: false
        }))
        if (this.tableData.length > 0) {
          this.$root.eventBus.$emit('event:log-list', this.tableData)

          this.rowClick(this.tableData[0])
        }
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.$emit('update:loading', false)
      }
    },
    rowClick (row) {
      this.$refs.table.setCurrentRow(row)
      if (window.getInfoApi) window.getInfoApi()
      if (window.getConnectorLogDetail) window.getConnectorLogDetail()
      this.$root.eventBus.$emit('event:row-click', row)
      this.selectRow = row
      this.getLogsSync(this.selectRow)
    },
    async getLogsSync () {
      const { get, set } = this._
      const { getConnectorDetailInfo } = this.$interface.apiManager
      const { status } = this.searchForm
      try {
        this.$emit('update:loading', true)

        const params = {
          subjectCode: get(this.data, 'sync.subjectCode')
        }

        if (status !== '') {
          set(params, 'status', status)
        }

        let { data: response } = await getConnectorDetailInfo(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }
        this.tableData = []
        this.tableData = get(response, 'data', []).map(i => ({
          ...i,
          loading: false
        }))
        let findIndex = this.tableData.findIndex(item => item.action === this.selectRow.action)
        this.$refs.table.setCurrentRow(this.tableData[findIndex])
        if (window.getConnectorLogDetail) window.getConnectorLogDetail()
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.$emit('update:loading', false)
      }
    },

  },
  destroyed () {
    clearInterval(this.timers)
  }
}
</script>

<style lang="scss" scoped>
.log-list {
  &__header {
    &--title {
      font-size: 16px;
      color: #404040;
      font-weight: 600;
    }
  }
  &__content {
    margin: 15px 0;
    .el-table {
      width: 100%;
      border: 1px solid #ebeef5;
      border-bottom: 0;
    }
    ::v-deep .log_list_headers {
      height: 48px;
      box-shadow: 1px 1px 0px 0px #f0f0f0;
      border-radius: 2px 0px 0px 0px;
      padding: 0;
    }
    .table-status {
      width: 84px;
      height: 24px;
      line-height: 20px;
      margin: 0 auto;
    }
  }

  .status_succes {
    background: #f0f9eb;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #67c23a;
    padding: 2px 8px;
  }
  .status_nosucces {
    background: #fef0f0;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #f56c6c;
    padding: 2px 8px;
  }
  .status_warning {
    background: #fef0f0;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #e6a23c;
    padding: 2px 8px;
  }
  .status_pedding {
    background: #e6f7ff;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #138dc7;
    padding: 2px 8px;
  }
}

.table-button {
  font-weight: 400;
  height: 28px;
  width: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
